<template>
  <div class="search-result">
    <van-list
  v-model="loading"
  :finished="finished"
  finished-text="没有更多了"

  :error.sync="error"
   error-text="请求失败，点击重新加载"
  @load="onLoad"
>
    <van-cell
   v-for="(value,index) in list" :key="index"
     :title="value.title" icon="search"></van-cell>
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search.js'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      loading: false,
      finished: false,
      page: 1,
      perPage: 20,
      list: [],
      error: false
    }
  },
  computed: {},
  watch: {},
  created () {

  },
  mounted () {},
  methods: {

    async onLoad () {
      try {
        const { data } = await getSearchResult({
          page: this.page, // 页码
          per_page: this.perPage, // 每页大小
          q: this.searchText // 搜索关键字

        })

        /* 通过这个模拟随即失败
        if (Math.random() > 0.5) {
            JSON.parse('dsnajndjsa')
        }
        */
        const res = data.data.results

        this.list.push(...res)
        this.loading = false
        if (res.length) {
          this.page++
        } else { this.finished = true }
      } catch (error) {
        // 展示加载失败的提示状态
        this.error = true

        // 加载失败了 loading 也要关闭
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
